package cn.tjad.tjad2.module.plan.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatSpinner;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bruce.pickerview.popwindow.DatePickerPopWin;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.fragment.BaseFragment;

import org.greenrobot.eventbus.EventBus;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.Task;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.data.event.PlanTaskEditEvent;
import cn.tjad.tjad2.data.session.ProjectUsers;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;
import cn.tjad.tjad2.module.plan.TaskEditRequestBean;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.ProgressDialogUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;

@Route(path = PageId.PLAN_TASK_EDIT)
public class PlanTaskEditFragment extends BaseFragment implements ProjectUsers.OnProjectUserListener {

    @BindView(R.id.task_name_value)
    EditText taskNameET;
    @BindView(R.id.task_plan_start_time)
    TextView planStartTimeTV;
    @BindView(R.id.task_plan_end_time)
    TextView planEndTimeTV;
    @BindView(R.id.task_actual_start_time)
    TextView actualStartTimeTV;
    @BindView(R.id.task_actual_end_time)
    TextView actualEndTimeTV;
    @BindView(R.id.task_response_user)
    AppCompatSpinner responseSpinner;

    private Task task;


    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.plan_task_edit, null);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getArguments() != null) {
            task = (Task) getArguments().getSerializable(Keys.TASK_ITEM);
        }
        if (task == null) {
            Tools.showToast("传入的task不能为空");
            getActivity().finish();
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        planStartTimeTV.setOnClickListener(this::onClick);
        planEndTimeTV.setOnClickListener(this::onClick);
        actualStartTimeTV.setOnClickListener(this::onClick);
        actualEndTimeTV.setOnClickListener(this::onClick);
        fillPageData();
    }

    private void fillPageData() {
        taskNameET.setText(task.name);
        planStartTimeTV.setText(task.planStartTime);
        planEndTimeTV.setText(task.planEndTime);
        actualStartTimeTV.setText(task.actualStartTime);
        actualEndTimeTV.setText(task.actualEndTime);
        if (task.children != null && task.children.size() > 0) {
            planStartTimeTV.setEnabled(true);
            planEndTimeTV.setEnabled(true);
            actualStartTimeTV.setEnabled(true);
            actualEndTimeTV.setEnabled(true);
        } else {
            planStartTimeTV.setEnabled(false);
            planEndTimeTV.setEnabled(false);
            actualStartTimeTV.setEnabled(false);
            actualEndTimeTV.setEnabled(false);
        }
        ProjectUsers.getInstance().getProjectUsers(this);
    }

    @Override
    public void onProjectUserGet(List<User> userList) {
        User empty = new User();
        empty.id = -1;
        empty.name = "";
        List<User> spinnerData = new ArrayList<>();
        spinnerData.add(empty);
        spinnerData.addAll(userList);
        ArrayAdapter<User> spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, spinnerData);
        responseSpinner.setAdapter(spinnerAdapter);
        User respondUser = task.user;
        if (respondUser != null) {
            int index = findIndex(userList, respondUser);
            if (index != -1) {
                responseSpinner.setSelection(index + 1);
            } else {
                responseSpinner.setSelection(0);
            }
        } else {
            responseSpinner.setSelection(0);
        }
    }

    private int findIndex(List<User> userList, User user) {
        if (userList == null || user == null) {
            return -1;
        }
        for (int i = 0; i < userList.size(); i++) {
            if (user.id == userList.get(i).id) {
                return i;
            }
        }
        return -1;
    }

    private TextView clickedDateView;

    @OnClick({R.id.save, R.id.cancel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.save:
                saveTaskEdit();
                break;
            case R.id.cancel:
                getActivity().finish();
                break;
            case R.id.task_plan_start_time:
            case R.id.task_plan_end_time:
            case R.id.task_actual_start_time:
            case R.id.task_actual_end_time:
                clickedDateView = (TextView) view;
                String date = clickedDateView.getText().toString();
                showDatePickDialog(date);
                break;
        }
    }

    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private void showDatePickDialog(String date) {
        if (TextUtils.isEmpty(date)) {
            date = dateFormat.format(new Date());
        }
        DatePickerPopWin datePickerPopWin = new DatePickerPopWin.Builder(getContext(), new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                if (clickedDateView != null) {
                    clickedDateView.setText(dateDesc);
                }
            }
        }).textCancel("取消")
                .textConfirm("确定")
                .btnTextSize(16)
                .viewTextSize(25)
                .minYear(1990)
                .maxYear(2500)
                .showDayMonthYear(true)
                .dateChose(date)
                .build();
        datePickerPopWin.showPopWin(getActivity());
    }

    private void saveTaskEdit() {
        String taskName = taskNameET.getText().toString();
        if (TextUtils.isEmpty(taskName)) {
            Tools.showToast("任务名称不能为空");
            return;
        }
        User user = (User) responseSpinner.getSelectedItem();
        if (user.id == -1) {
            Tools.showToast("责任人不能为空");
            return;
        }
        TaskEditRequestBean requestBean = new TaskEditRequestBean();
        requestBean.id = task.id;
        requestBean.name = taskName;
        requestBean.planStartTime = planStartTimeTV.getText().toString().trim();
        requestBean.planEndTime = planEndTimeTV.getText().toString().trim();
        requestBean.actualStartTime = actualStartTimeTV.getText().toString().trim();
        requestBean.actualEndTime = actualEndTimeTV.getText().toString().trim();
        requestBean.user  = new TaskEditRequestBean.User();
        requestBean.user.id = user.id;
        ProgressDialogUtils.show(getContext());
        RetrofitManager.getInstance().getApiService()
                .updatePlanProgress(Tools.getProjectId(), task.id, requestBean)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        ProgressDialogUtils.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
                                .setTitle("提示")
                                .setMessage("保存成功")
                                .setCancelable(false)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        PlanTaskEditEvent event = new PlanTaskEditEvent(true);
                                        EventBus.getDefault().post(event);
                                        getActivity().finish();
                                    }


                                });
                        builder.show();
                    }

                    @Override
                    public void onFailed(String message) {
                        ProgressDialogUtils.dismiss();
                        Tools.showToast(message);
                    }
                });

    }
}
